package com.etc.classdemo;

import java.lang.reflect.InvocationTargetException;
import java.util.Scanner;

public class TestCreateNewInstance {
    public static void main(String[] args) throws ClassNotFoundException, InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException {
        //输入(控制台，文件文本，xml，properties,json等等)
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入您要创建的类，包含完整的包: 例如 java.lang.String");
        String str = scanner.next();
        //使用Class类型对象来处理

        Class cls = Class.forName(str);
        Object instance = getInstance(cls);
        //就是特定类型对象
        System.out.println("instance: "+instance);
    }

    /**
     *
     * @param cls  是Class类型的对象
     * @return
     * @throws NoSuchMethodException
     * @throws InvocationTargetException
     * @throws InstantiationException
     * @throws IllegalAccessException
     */
    public  static  Object getInstance(Class cls) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        Object o = cls.getDeclaredConstructor().newInstance();
        return  o;
    }
}
